package com.bs.web.rest;

import com.bs.domain.PartitionIp2Host;
import com.bs.service.PartitionIp2HostService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wenguangjia on 2017/8/16.
 */
@RestController
@RequestMapping("/api/partitionip2host")
public class PartitionIp2HostResource {
    @Autowired
    private PartitionIp2HostService service;
    private final Logger log = LoggerFactory.getLogger(PartitionIp2HostResource.class);

    @PostMapping("/search")
    @ResponseBody
    public List<PartitionIp2Host> search(@RequestBody PartitionIp2Host partitionIp2Host) {
        List<PartitionIp2Host> partitionIp2Hosts = service.getAll(partitionIp2Host);
        return partitionIp2Hosts;
    }

    @PostMapping("/save")
    public void save(@RequestBody PartitionIp2Host partitionIp2Host) {
        service.save(partitionIp2Host);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Long id) {
        service.delete(id);
    }

    @GetMapping("/trace")
    @ResponseBody
    public void getFile(@RequestParam("hostName") String hostName, @RequestParam("fileName") String fileName,
                        @RequestParam("logTime") String logTime, HttpServletResponse response) throws IOException, ParseException {

        PartitionIp2Host partitionIp2Host = new PartitionIp2Host();
        partitionIp2Host.setHost(hostName);
        List<PartitionIp2Host> partitionIp2Hosts = service.getAll(partitionIp2Host);
        String ip = partitionIp2Hosts.get(0).getIp();
        URL url = getAddress(fileName, logTime, ip);
//          URL url = new URL("http://190.2.241.32:8001/Trace/pmoasi01_alc.0712.17367202");
        InputStream is = url.openStream();
        int count = getFileSize(url);
        response.setContentType("application/octet-stream");
        response.setContentLength(count);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("If-Modified-Since", "0");
        try {
            IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("Error writing file to output stream. Filename was '{}'", fileName, e);
            throw new RuntimeException("IOError writing file to output stream");
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    private static int getFileSize(URL url) {
        URLConnection conn = null;
        try {
            conn = url.openConnection();
            if (conn instanceof HttpURLConnection) {
                ((HttpURLConnection) conn).setRequestMethod("HEAD");
            }
            conn.getInputStream();
            return conn.getContentLength();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (conn instanceof HttpURLConnection) {
                ((HttpURLConnection) conn).disconnect();
            }
        }
    }


    private URL getAddress(String fileName, String logTime, String ip) throws MalformedURLException, ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = format.parse(logTime.split(" ")[0]);
        long time1 = date1.getTime() / 1000;
        Date date2 = new Date();
        long time2 = date2.getTime() / 1000;
        long time = (time2 - time1) / (3600 * 24);
        String address = "http://" + ip + ":8001/Trace/" + fileName;
        if (time != 0) {
            address = "http://" + ip + ":8001/Trace." + time + "/" + fileName;
        }
        return new URL(address);

    }

}
